package logic

import (
	"beike/models"
	"context"

	"beike/houserpc/houserpc"
	"beike/houserpc/internal/svc"

	"github.com/zeromicro/go-zero/core/logx"
)

type HouseListLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewHouseListLogic(ctx context.Context, svcCtx *svc.ServiceContext) *HouseListLogic {
	return &HouseListLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *HouseListLogic) HouseList(in *houserpc.HouseListRequest) (*houserpc.HouseListResponse, error) {
	// todo: add your logic here and delete this line

	offset := (in.Page - 1) * in.Size

	var houses []models.UserHouse

	tx := models.DB.Debug().Model(&models.House{}).Offset(int(offset)).Limit(int(in.Size)).
		Select("houses.*,users.nick_name as nick_name").
		Joins("left join users on users.id = houses.user_id")

	if in.PriceOrder == 1 {
		tx = tx.Order("price desc")
	}
	if in.PriceOrder == 2 {
		tx = tx.Order("price asc")
	}

	if in.CreatedAtOrder == 1 {
		tx = tx.Order("created_at desc")
	}
	if in.CreatedAtOrder == 2 {
		tx = tx.Order("created_at asc")
	}

	if in.Address != "" {
		tx = tx.Where("address like ?", "%"+in.Address+"%")
	}

	tx.Find(&houses)

	var houseList []*houserpc.HouseList

	for _, house := range houses {
		list := houserpc.HouseList{
			UserId:  house.UserId,
			Title:   house.Title,
			Intro:   house.Intro,
			Price:   float32(house.Price),
			Address: house.Address,
			Types:   house.Types,
			Area:    float32(house.Area),
		}
		houseList = append(houseList, &list)
	}

	return &houserpc.HouseListResponse{
		List: houseList,
	}, nil
}
